package com.ccb.sc.common.modules.goods.utils;

import com.ccb.sc.common.modules.goods.entity.Category;
import com.ccb.sc.common.modules.goods.vo.CategoryTreeVo;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author ken
 * @version 1.0
 * @date 2020-09-14
 */
public class TreeCategoryUtil {

    private static final Comparator<Category> COMPARATOR = (s, t) -> {
        if (s.getParentId().equals(t.getParentId())) {
            return Optional.ofNullable(s.getOrders()).orElse(0) - Optional.ofNullable(t.getOrders()).orElse(0);
        }
        return s.getParentIds().compareTo(t.getParentIds());
    };

    public static List<CategoryTreeVo> convertToTreeResource(List<Category> categories, boolean removeNoLeaf) {
        if (CollectionUtils.isEmpty(categories)) {
            return Collections.emptyList();
        }
        CategoryTreeVo root = new CategoryTreeVo();
        root.setKey(0L);
        root.setValue("root");
        //对原resource 排序
        categories.sort(COMPARATOR);
        recursive(root, categories);
        List<CategoryTreeVo> resultTree = root.getChildren();
        if (removeNoLeaf) {
            removeNoLeaf(resultTree);
        }
        return resultTree;
    }

    private static void recursive(CategoryTreeVo parent, List<Category> categories) {
        Iterator<Category> iterator = categories.iterator();
        while (iterator.hasNext()) {
            Category category = iterator.next();
            if (category.getParentId().equals(parent.getKey())) {
                parent.getChildren().add(convert(category));
                iterator.remove();
            }
        }
        for (CategoryTreeVo node : parent.getChildren()) {
            recursive(node, categories);
        }
    }

    private static CategoryTreeVo convert(Category category) {
        CategoryTreeVo categoryTreeVo = new CategoryTreeVo();
        categoryTreeVo.setKey(category.getId());
        categoryTreeVo.setValue(category.getName());
        categoryTreeVo.setIcon(category.getIcon());
        categoryTreeVo.setParentId(category.getParentId());
        return categoryTreeVo;
    }

    private static void removeNoLeaf(List<CategoryTreeVo> tree) {
        if (CollectionUtils.isEmpty(tree)) {
            return;
        }
        Iterator<CategoryTreeVo> iterator = tree.iterator();
        while (iterator.hasNext()) {
            CategoryTreeVo node = iterator.next();
            removeNoLeaf(node.getChildren());
            if (!node.isHasChildren() && !StringUtils.hasText((String) node.getValue())) {
                iterator.remove();
            }
        }
    }
}
